package com.ronsai.umtrack.api.converter;

import com.google.gson.TypeAdapter;
import com.ronsai.umtrack.api.exception.ApiException;
import com.ronsai.umtrack.api.exception.TokenEmptyException;
import com.ronsai.umtrack.api.exception.TokenExpiredException;
import com.ronsai.umtrack.base.BaseResponse;

import java.io.IOException;

import okhttp3.ResponseBody;
import retrofit2.Converter;

final class GsonResponseBodyConverter<T> implements Converter<ResponseBody, Object> {
    private final TypeAdapter<T> adapter;

    GsonResponseBodyConverter(TypeAdapter<T> adapter) {
        this.adapter = adapter;
    }

    @Override
    public Object convert(ResponseBody value) throws IOException {
        try {
            BaseResponse baseResponse = (BaseResponse) adapter.fromJson(value.charStream());
            if (baseResponse.getCode() == 2) {
                throw new TokenEmptyException();
            } else if (baseResponse.getCode() == 3) {
                throw new TokenExpiredException();
            } else if (baseResponse.getCode() != 1) {
                throw new ApiException(baseResponse.getCode(), baseResponse.getMsg());
            } else {
                return baseResponse.getData();
            }
        } finally {
            value.close();
        }
    }
}
